package com.example.dense_rack_server.controller.dataBackup;


import cn.hutool.json.JSONObject;
import com.example.dense_rack_server.entity.NodeInfo;
import com.example.dense_rack_server.entityVo.dataBackup.BackupReqVO;
import com.example.dense_rack_server.entityVo.dataBackup.NodeProperties;
import com.example.dense_rack_server.service.dataBackup.NodeInfoService;
import com.example.dense_rack_server.utils.DataBackup.DataSourceUtil;
import com.example.dense_rack_server.utils.ResponseModel;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * MySQL连接信息 前端控制器
 * </p>
 *
 * @author  张彬 
 * @since 2025-07-01
 */
@Controller
@RequestMapping("/backup/node/info")
public class NodeInfoController {

    @Autowired
    private NodeInfoService nodeInfoService;

    /**
     * 实例管理首页
     */
    @GetMapping("")
    public String list(Model model) {
        return "DataBackup/nodeInfo/index";
    }


    /**
     * 实例信息分页查询
     */
    @GetMapping("list")
    @ResponseBody
    public Map<String, Object> tableList(@RequestParam(value = "name", required = false) String name,
                                    @RequestParam(value = "host", required = false) String host,
                                    @RequestParam(value = "port", required = false) String port,
                                    @RequestParam(value = "page") int page,
                                    @RequestParam(value = "limit") int limit) {
        return nodeInfoService.tableList(page, limit, name, host, port);
    }


    /**
     * 实例管理新增页
     */
    @GetMapping("/add")
    public String add() {
        return "DataBackup/nodeInfo/add";
    }

    /**
     * 实例信息新增
     */
    @PostMapping("add")
    @ResponseBody
    public ResponseModel add(@RequestBody NodeInfo nodeInfo) {
        return nodeInfoService.add(nodeInfo);
    }


    /**
     * 实例信息测试连接
     */
    @PostMapping("connect")
    @ResponseBody
    public ResponseModel connect(@RequestBody NodeProperties properties) {
        try (HikariDataSource dataSource = DataSourceUtil.createDataSource(properties)) {
            if (dataSource.isRunning()) {
                return ResponseModel.success("连接成功");
            }
        } catch (Exception e) {
            return ResponseModel.fail("连接失败：" + e.getMessage());
        }
        return ResponseModel.fail("连接失败");
    }


    /**
     * 删除实例信息
     */
    @PostMapping("delete")
    @ResponseBody
    public ResponseModel delete(@RequestBody JSONObject data) {
        nodeInfoService.removeById(data.getInt("id"));
        return ResponseModel.success("删除成功");
    }


    /**
     * 实例信息编辑页
     */
    @GetMapping("/update/{id}")
    public ModelAndView update(@PathVariable("id") String id) {
        NodeInfo nodeInfo =  nodeInfoService.getById(id);
        ModelAndView modelAndView = new ModelAndView("DataBackup/nodeInfo/update");
        modelAndView.addObject("nodeInfo", nodeInfo);
        return modelAndView;
    }

    /**
     * 档案装具修改保存
     */
    @PostMapping("/edit/update")
    @ResponseBody
    public ResponseModel editUpdate(@RequestBody NodeInfo nodeInfo) {
        nodeInfoService.updateById(nodeInfo);
        return ResponseModel.success("修改成功");
    }


    /**
     * 实例管理备份页
     */
    @GetMapping("node-info-backup/{id}")
    public String backup(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("data", nodeInfoService.getById(id));
        return "DataBackup/nodeInfo/backup";
    }


    /**
     * 获取数据库所有表信息
     */
    @PostMapping("listTables")
    @ResponseBody
    public ResponseModel listTables(@RequestBody NodeProperties properties) {
        try (HikariDataSource dataSource = DataSourceUtil.createDataSource(properties)) {
            if (dataSource.isRunning()) {
                List<String> strings = DataSourceUtil.listTables(dataSource);
                return ResponseModel.success(strings,"操作成功");
            }
        } catch (Exception e) {
            return ResponseModel.fail("连接失败：" + e.getMessage());
        }
        return ResponseModel.fail("获取数据表信息失败");
    }


    /**
     * 获取实例信息数据库列表
     * @param properties
     * @return
     */
    @PostMapping("listDatabases")
    @ResponseBody
    public ResponseModel listDatabases(@RequestBody NodeProperties properties) {
        try (HikariDataSource dataSource = DataSourceUtil.createDataSource(properties)) {
            if (dataSource.isRunning()) {
                List<String> strings = DataSourceUtil.listDataBases(dataSource);
                return ResponseModel.success(strings,"操作成功");
            }
        } catch (Exception e) {
            return ResponseModel.fail("连接失败：" + e.getMessage());
        }
        return ResponseModel.fail("获取数据库信息失败");
    }


    /**
     * 保存备份（立即备份，备份任务）
     */
    @PostMapping("saveBackUp")
    @ResponseBody
    public ResponseModel saveBackUp(@RequestBody BackupReqVO reqVO) {
        return nodeInfoService.saveBackUp(reqVO);
    }
}
